#include <iostream>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>

//将一个阻塞的文件描述符,转换为非阻塞的文件描述符
//我们这里以读取为例子

void set_none_block(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        std::cerr << "fcntl" << std::endl;
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}


int main()
{
    set_none_block(0);
    while(true)
    {
        //如果读取成功了,那么错误码是不会进行设置的,只有失败了才会进行设置,这一点我们需要进行注意
        errno = 0;
        char buffer[1024] = {0};
        ssize_t ret = read(0, buffer, sizeof(buffer) - 1);
        if (ret > 0)
        {
            buffer[ret] = '\0';
            write(1, buffer, strlen(buffer));
           std::cout << "read success ret = " << ret << " errno = " << errno << std::endl;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "数据还没有准备好!" << std::endl;
                std::cout << "read failed ret = " << ret << " errno = " << errno << std::endl;
                sleep(1);
            }
        }
    }
    return 0;
}
